package com.open.capacity.notice.provider.core.http;

import java.util.function.BiFunction;

import org.springframework.util.StringUtils;

import com.open.capacity.notice.provider.core.constant.CommonConstant;

import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 动态构造okhttp请求参数
 * 
 */
public enum HttpMethod {

	/**
	 * get request.
	 */
	GET("GET", (builder, bodyStr) -> {
		return builder.get();
	}),
	/**
	 * head request.
	 */
	HEAD("HEAD", (builder, bodyStr) -> {
		return builder.head();
	}),
	/**
	 * post request.
	 */
	POST("POST", (builder, bodyStr) -> {
		return builder.post(RequestBody.create(CommonConstant.APPLICATION_JSON_UTF8, bodyStr));
	}),
	/**
	 * put request.
	 */
	PUT("PUT", (builder, bodyStr) -> {
		return builder.put(RequestBody.create(CommonConstant.APPLICATION_JSON_UTF8, bodyStr));
	}),
	/**
	 * patch request.
	 */
	PATCH("PATCH", (builder, bodyStr) -> {
		return builder.patch(RequestBody.create(CommonConstant.APPLICATION_JSON_UTF8, bodyStr));
	}),
	/**
	 * delete request.
	 */
	DELETE("DELETE", (builder, bodyStr) -> {
		return StringUtils.hasText(bodyStr)
				? builder.delete(RequestBody.create(CommonConstant.APPLICATION_JSON_UTF8, bodyStr))
				: builder.delete();
	}),
	/**
	 * options request.
	 */
	OPTIONS("OPTIONS", (builder, bodyStr) -> {
		return builder;
	}),
	/**
	 * trace request.
	 */
	TRACE("TRACE", (builder, bodyStr) -> {
		return builder;
	});

	private String name;
	private BiFunction<Request.Builder, String, Request.Builder> function;

	HttpMethod(String name, BiFunction<Request.Builder, String, Request.Builder> function) {
		this.name = name;
		this.function = function;
	}

	public String getName() {
		return name;
	}

	public Request.Builder apply(Request.Builder builder, String bodyStr) {
		return function.apply(builder, bodyStr);
	}

	public Request.Builder apply(Request.Builder builder) {
		return function.apply(builder, null);
	}

	public static HttpMethod getByName(int name) {
		for (HttpMethod type : HttpMethod.values()) {
			if (type.getName().equals(name)) {
				return type;
			}
		}
		return null;
	}

}
